<?php


namespace App\Http\Rest\Information\Resource;

use App\Http\Rest\Information\BaseResource;
use Framework\Foundation\Database\FDB;
use Framework\Foundation\Request\ServerRequest;
use App\Exceptions\BusinessException;
use Framework\Foundation\Response\ResponseGen;

class Information extends BaseResource
{


    /**
     * @param array $restParams
     * @param $request ServerRequest
     * @return array
     * @throws BusinessException
     */
    public function add(array $restParams, $request)
    {
        // 参数验证
        $params = $request->getParsedBody();
        $params['member_id'] = $request->getAttribute('member_id', 0);
        $ret = $this->resourceAdd($restParams['resource'], $params);

        if (!$ret) {
            throw new BusinessException("添加失败", 600);
        }
        return [];
    }

    public function edit(array $restParams, $request)
    {
        // 参数验证
        $params = $request->getParsedBody();
        if (isset($params['_ajax_method'])) {
            unset($params['_ajax_method']);
        }

        $ret = $this->resourceEdit($restParams['resource'], $restParams['field'], $restParams['id'], $params);
        if (!$ret) {
            throw new BusinessException("编辑失败", 600);
        }
        return [];
    }

    /**
     * @param array $restParams
     * @param ServerRequest $request
     * @return \Psr\Http\Message\ResponseInterface
     * @throws BusinessException
     * @throws \Envms\FluentPDO\Exception
     */
    public function delete(array $restParams, $request)
    {
        $memberId = $request->getAttribute('member_id', 0);

        $query = FDB::update($restParams['resource'])
            ->where($restParams['field'], $restParams['id'])
            ->where('member_id', $memberId);

        $ret = $query->set([
            'is_deleted' => 1,
            'deleted_at' => date('Y-m-d H:i:s')
        ])->execute();
        if (!$ret) {
            throw new BusinessException("删除失败:" . $query->getMessage(), 600);
        }
        return ResponseGen::success([], "删除成功");
    }
}
